/*
 * @Author: jiejie
 * @Github: https://github.com/jiejieTop
 * @Date: 2019-12-15 18:27:19
 * @LastEditTime : 2020-01-08 20:23:13
 * @Description: the code belongs to jiejie, please keep the author information and source code according to the license.
 */
#include "platform_mutex.h"
#include "platform_timer.h"

typedef void * sys_sem_t;
extern OSA_STATUS OsaSemaphoreCheck( OsaRefT OsaRef);

static int sys_sem_new(sys_sem_t *sem, uint8_t count)
{
    if (OS_SUCCESS == OSASemaphoreCreate(sem, count, OS_FIFO)) {
        return 0;
    } else {
        return -1;
    }
}

static int sys_sem_free(sys_sem_t *sem)
{
    if (OS_SUCCESS == OSASemaphoreCheck (*sem)) {
        OSASemaphoreDelete(*sem);   
        *sem = MQTT_RTOS_SEM_NULL;
        return 0;
    } else {
        return -1;
    }
}

static int sys_sem_signal(sys_sem_t *sem)
{
    if (OS_SUCCESS == OSASemaphoreCheck (*sem)) {
        OSASemaphoreRelease(*sem);
        return 0;
    } else {
        return -1;
    }
}

static int sys_sem_wait(sys_sem_t *sem, uint32_t timeout)
{
    OSA_STATUS  status;
    int count;

    if (OS_SUCCESS != OSASemaphoreCheck(*sem)) {
        return -1;
    }

    if (timeout == 0) {
        status = OSASemaphoreAcquire(*sem, OSA_SUSPEND);
    } else {
        count =  (timeout + (MQTT_RTOS_MS_ONE_TICK - 1)) / MQTT_RTOS_MS_ONE_TICK;
        status = OSASemaphoreAcquire(*sem, count);
    }

    if (OS_SUCCESS == status) {
        return 0;
    }

    return -1;
}


int platform_mutex_init(platform_mutex_t* m)
{
    return sys_sem_new(&(m->mutex), 1);
}

int platform_mutex_lock(platform_mutex_t* m)
{
    return sys_sem_wait(&(m->mutex), 0);
}

int platform_mutex_unlock(platform_mutex_t* m)
{
    return sys_sem_signal(&(m->mutex));
}

int platform_mutex_destroy(platform_mutex_t* m)
{
    return sys_sem_free(&(m->mutex));
}
